package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.annotation.Incomplete;
import org.aeon.message.request.GroupJoinRequestMessage;
import org.aeon.message.response.GroupJoinResponseMessage;
import org.aeon.service.ChatGroupService;
import org.aeon.service.UserGroupRelationService;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.UserGroupRelationServiceFactory;

/**
 * @author: MissingAeon
 * @date: 2024/2/19 8:54
 * @description: 加入群聊请求处理器
 */
@Slf4j
@ChannelHandler.Sharable
@Incomplete
public class GroupJoinRequestHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        final GroupJoinResponseMessage resMsg = new GroupJoinResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final Long chatGroupId = msg.getGroupId();
        final ChatGroupService groupService = ChatGroupServiceFactory.getService();
        // 判断群聊是否存在
        if (groupService.isChatGroupExist(chatGroupId)) {
            final UserGroupRelationService groupRelationService = UserGroupRelationServiceFactory.getService();
            final Long userId = msg.getUserId();
            // 判断查询用户是否为群聊成员
            if (!groupRelationService.isGroupMember(chatGroupId, userId)) {
                final int i = groupRelationService.insertBatchUserGroupRelation(chatGroupId, userId);

                if (i == 1) resMsg.setResponse(true, "加入群聊成功");
                else resMsg.setResponse(false, "加入群聊失败");

            } else {
                resMsg.setResponse(false, "已是该群聊成员");
            }
        } else {
            resMsg.setResponse(false, "该群聊不存在");
        }
        ctx.writeAndFlush(msg);
    }
}
